package com.horizon.common.configuration;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * 声明式事务配置
 *
 * @author wangfuwei
 * @version 2018-08-07
 */
@ConditionalOnBean(PlatformTransactionManager.class)
@SpringBootConfiguration
public class TransactionConfiguration {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean(name = "txAdvice")
    public TransactionInterceptor transactionInterceptor() {
        Properties properties = new Properties();

        for (String key : new String[]{"persist*", "save*", "add*", "create*", "remove*", "delete*", "merge*", "update*", "copy*", "clone*", "sync*"}) {
            properties.setProperty(key, "PROPAGATION_REQUIRED,-Exception");
        }

        for (String key : new String[]{"find*", "get*", "load*", "query*"}) {
            properties.setProperty(key, "PROPAGATION_REQUIRED,-Exception,readOnly");
        }

        TransactionInterceptor tsi = new TransactionInterceptor(transactionManager, properties);
        return tsi;
    }

    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*Service", "*ServiceImpl");
        creator.setProxyTargetClass(true);
        return creator;
    }
}
